<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\facade\Log;
use app\user\model\UserModel;
use cmf\controller\AdminBaseController;
use think\db\Query;
use api\mall\model\StoreLogModel;

/**
 * Class UserController
 * @package app\user\controller
 *
 * @adminMenuRoot(
 *     'name'   =>'用户管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 10,
 *     'icon'   =>'group',
 *     'remark' =>'用户管理'
 * )
 *
 * @adminMenuRoot(
 *     'name'   =>'用户组',
 *     'action' =>'default1',
 *     'parent' =>'user/AdminIndex/default',
 *     'display'=> false,
 *     'order'  => 10000,
 *     'icon'   =>'',
 *     'remark' =>'用户组'
 * )
 */
class UserListController extends AdminBaseController
{

    /**
     * 后台本站用户列表
     * @adminMenu(
     *     'name'   => '本站用户',
     *     'parent' => 'user/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('user_admin_index_view');

        if (!empty($content)) {
            return $content;
        }

        $filter = $this->request->param();
        $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
        $endTime   = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        if (!empty($startTime) && !empty($endTime) && $startTime >= $endTime) {
            // $this->error("截止日期需大于起始日期");
            $tempTime = $filter['start_time'];
            $filter['start_time'] = $filter['end_time'];
            $filter['end_time'] = $tempTime;

            $tempTime = $startTime;
            $startTime = $endTime;
            $endTime = $tempTime;
        }

        if (isset($filter['mobile']) && !empty($filter['mobile'])) {
            $mobile = $filter['mobile'];
            if (!cmf_check_mobile($mobile)) {
                $this->assign('mobile_error', '请输入正确的手机号码');
            }
        }
        
        $this->assign('uid', isset($filter['uid']) ? $filter['uid'] : '');
        $this->assign('mobile', isset($filter['mobile']) ? $filter['mobile'] : '');
        $this->assign('user_status', isset($filter['user_status']) ? $filter['user_status'] : '');
        $this->assign('time_type', isset($filter['time_type']) ? $filter['time_type'] : '');
        $this->assign('start_time', isset($filter['start_time']) ? $filter['start_time'] : '');
        $this->assign('end_time', isset($filter['end_time']) ? $filter['end_time'] : '');
        
        $list = UserModel::where(function (Query $query) {
            $data = $this->request->param();
            if (!empty($data['uid'])) {
                $query->where('user_id', intval($data['uid']));
            }

            // if (!empty($data['keyword'])) {
            //     $keyword = $data['keyword'];
            //     $query->where('user_login|user_nickname|user_email|mobile', 'like', "%$keyword%");
            // }
            
            if (!empty($data['mobile'])) {
                $query->where('mobile', $data['mobile']);
            }
            
            if (!empty($data['user_status'])) {
                $query->where('user_status', $data['user_status'] == 2 ? 0 : $data['user_status']);
            }

            $startTimeQuery = empty($data['start_time']) ? 0 : strtotime($data['start_time']);
            $endTimeQuery   = empty($data['end_time']) ? 0 : strtotime($data['end_time']);
            if (!empty($startTimeQuery) && !empty($endTimeQuery) && $startTimeQuery >= $endTimeQuery) {
                $tempTime = $startTimeQuery;
                $startTimeQuery = $endTimeQuery;
                $endTimeQuery = $tempTime;
            }
            
            Log::info('开始时间：' . $startTimeQuery . '，结束时间：' . $endTimeQuery); 
            Log::info('开始时间：' . date('Y-m-d H:i:s', $startTimeQuery) . '，结束时间：' . date('Y-m-d H:i:s', $endTimeQuery + 86400)); 

            if (!empty($startTimeQuery) && !empty($endTimeQuery)) {
                $endTimeQuery = $endTimeQuery + 86400;
                switch ($data['time_type']) {
                    case '1':
                        $query->where('create_time', '>=', $startTimeQuery);
                        $query->where('create_time', '<=', $endTimeQuery);
                        break;
                    case '2':
                        $query->where('last_login_time', '>=', $startTimeQuery);
                        $query->where('last_login_time', '<=', $endTimeQuery);
                        break;
                    case '3':
                        $query->where('pay_time', '>=', $startTimeQuery);
                        $query->where('pay_time', '<=', $endTimeQuery);
                        break;
                }
            }
        })->order("create_time DESC")->paginate(20);
//        })->alias('u')->where('log.status','>',0)
//                ->field('u.*,sum(log.cost) cost,log.pay_time')->join('store_log log','u.id=log.user_id','left')->group('u.id')->order("u.create_time DESC")
//            ->paginate(10);
 // 打印list
        $uids = [];
        foreach ($list as $v){
            $uids[] = $v->id;
        }
        $log = new StoreLogModel();
        $data = $log->whereIn('user_id',$uids)->where('status','>',0)->field('user_id,sum(cost) cost')->group('user_id')->select();
        
        $data_list = [];
        foreach ($list as $v){
            foreach ($data as $v2){
                if($v2['user_id']==$v->id){
                    $v->cost = $v2['cost'];
                }
            }
            $data_list[] = $v;
        }
        
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $data_list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch('user/index');
    }

    /**
     * 本站用户拉黑
     * @adminMenu(
     *     'name'   => '本站用户拉黑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户拉黑',
     *     'param'  => ''
     * )
     */
    public function ban()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
            $result = UserModel::where(["id" => $id, "user_type" => 2])->update(['user_status' => 0]);
            if ($result) {
                $this->success("会员拉黑成功！", "adminIndex/index");
            } else {
                $this->error('会员拉黑失败,会员不存在,或者是管理员！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 本站用户启用
     * @adminMenu(
     *     'name'   => '本站用户启用',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户启用',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
            $result = UserModel::where(["id" => $id, "user_type" => 2])->update(['user_status' => 1]);
            if ($result) {
                $this->success("会员启用成功！", "adminIndex/index");
            } else {
                $this->error('会员启用失败,会员不存在,或者是管理员！');
            }
        } else {
            $this->error('数据传入失败！');
        }
    }
}
